window.onload = function () {
	let newList = list //备份数据，方便修改
	let userList = [] //获取列表每一项
	rendering(newList) //初始渲染

	//搜索按钮
	search.addEventListener("click", () => update(document.querySelector('[name="name"]').value, document.querySelector('[name="gender"]').value, document.querySelector('[name="age"]').value))

	//重置按钮
	reset.addEventListener("click", () => {
		document.querySelector('[name="name"]').value = ""
		document.querySelector('[name="gender"]').value = ""
		document.querySelector('[name="age"]').value = ""
		update("", "", "") //更新
	})

	//删除按钮
	function deleteBtn() {
		document.querySelectorAll("#tbody tr td .btn").forEach(ele => {
			ele.addEventListener("click", function () {
				const id = this.parentNode.parentNode.children[0].innerText
				newList.forEach((item, index) => item.id == id && newList.splice(index, 1))
				rendering(newList) //重新渲染
			})
		})
	}

	//搜索更新
	function update(name, gender, age) {
		userList.forEach(item => {
			item.style.display = "table-row"
			name != item.children[1].innerText && name && (item.style.display = "none")
			gender != item.children[2].innerText && gender && (item.style.display = "none")
			age != item.children[3].innerText && age && (item.style.display = "none")
		})
	}

	//渲染页面
	function rendering(arr = []) {
		tbody.innerHTML = ""
		arr.forEach(item => {
			tbody.innerHTML += `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.gender}</td>
                <td>${item.age}</td>
                <td>
                    <button type="button" class="btn btn-danger">删除</button>
                </td>
            </tr>`
		})
		userList = document.querySelectorAll("#tbody tr") //重新获取列表
		deleteBtn() //删除按钮注册事件
	}
}

/* 
    总结：
    我学会了：数组遍历、父子元素获取、箭头函数
    我还需加强：思维逻辑、代码优化
*/
